package com.yin.spring5.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

/**
 * JdkProxy
 *
 * @author Yin Guiqing
 */
public class JdkProxy {
    public static void main(String[] args) {
        // 创建接口实现类代理对象
        Class[] interfaces = {UserDao.class};
        UserDao userDao = new UserDaoImpl();
        UserDao proxyInstance =
                (UserDao) Proxy.newProxyInstance(JdkProxy.class.getClassLoader(),
                        interfaces, new UserDaoProxy(userDao));
        System.out.println(proxyInstance.add(2, 3));
        System.out.println(proxyInstance.update("abc"));
    }
}

// 创建代理对象代码
class UserDaoProxy implements InvocationHandler {
    private Object obj;

    // 把被代理对象传递过来
    public UserDaoProxy(Object obj) {
        this.obj = obj;
    }

    // 增强的逻辑
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 方法之前
        System.out.println(method.getName() + " 方法之前执行，参数：" + Arrays.toString(args));
        // 被增强的方法执行
        Object returnValue = method.invoke(obj, args);
        // 方法之后
        System.out.println(method.getName() + " 方法之后执行");
        return returnValue;
    }
}
